package impl

import (
	"context"

	"gitee.com/go-course/go12/devcloud-mini/cmdb/apps/resource"
	"github.com/infraboard/mcube/exception"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func (i *impl) Save(
	ctx context.Context,
	in *resource.Resource,
) (*resource.Resource, error) {
	i.log.Debug().Msgf("save resource ...")

	// 请求的校验
	if err := i.validator.Struct(in); err != nil {
		return nil, exception.NewBadRequest(err.Error())
	}

	// 请求的处理

	// 入库
	if _, err := i.col.InsertOne(ctx, in); err != nil {
		return nil, err
	}

	return in, nil
}

// list
func (i *impl) Search(
	ctx context.Context,
	in *resource.SearchRequest) (
	*resource.ResourceSet, error) {

	// json map 格式的filter {"filedA.FileedAB": "a"}   where filedA=a
	// 1. 条件过滤
	filter := bson.M{}
	// 精确匹配
	if in.Type != nil {
		filter["spec.resource_type"] = *in.Type
	}
	// 模糊匹配
	if in.Keywords != "" {
		// LIKE
		filter["spec.name"] = bson.M{"$regex": in.Keywords, "$options": "im"}
	}

	// 2. 分页
	options := options.Find()
	options.SetLimit(int64(in.Page.PageSize))
	options.SetSkip(in.Page.ComputeOffset())
	i.log.Debug().Msgf("filter: %s", filter)
	cur, err := i.col.Find(ctx, filter, options)
	if err != nil {
		return nil, err
	}

	set := resource.NewResourceSet()
	for cur.Next(ctx) {
		ins := resource.NewResource()
		// 获取一个doc
		if err := cur.Decode(ins); err != nil {
			return nil, err
		}
		set.Items = append(set.Items, ins)
	}

	// 查询总数
	set.Total, err = i.col.CountDocuments(ctx, filter)
	if err != nil {
		return nil, err
	}

	return set, nil
}
